import {
  login,
  logout,
  getSmsCode,
  smsLogin,
  updatePassWord,
  forgetPassWord
} from '@/api'
import { Reducer, Effect, Subscription } from 'umi'
import { ResultType } from '@/types/index'
import { setStorage } from '@/utils'
export interface LoginStateType {
  userName: string
  token: string
  userId: string
  permissions: string
  faceFileUrl: string
}
interface LoginModelType {
  namespace: string
  state: LoginStateType
  reducers: {
    setState: Reducer<LoginStateType>
  }
  effects: {
    function_login: Effect
    function_logout: Effect
    function_getSmsCode: Effect
    function_smsLogin: Effect
    function_updatePassWord: Effect
    function_forgetPassWord: Effect
  }
  subscriptions: {
    setup: Subscription
  }
}

export default <LoginModelType>{
  namespace: 'login',
  state: {
    // 用户姓名
    userName: '',
    // token值
    token: '',
    //  用戶id
    userId: '',
    //  當前用戶能夠訪問的系統
    permissions: '',
    // 头像地址
    faceFileUrl: ''
  },
  reducers: {
    setState(state, action) {
      return { ...state, ...action.payload }
    }
  },
  effects: {
    // 用户登录
    *function_login({ payload, callback }, { call, put }) {
      const { accountName, accountPass } = payload
      const res: ResultType = yield call(login, accountName, accountPass)
      if (res.code != 200) {
        return
      }
      callback(res)
      setStorage('userCode', (res.obj as { userCode: string }).userCode)
      yield put({
        type: 'setState',
        payload: {
          time: res
        }
      })
    },
    // 注销登录
    *function_logout({ callback }, { call }) {
      const res: ResultType = yield call(logout)
      callback(res)
    },
    // 获取手机短信验证码
    *function_getSmsCode({ payload: { phone }, callback }, { call }) {
      const res: ResultType = yield call(getSmsCode, phone)
      callback(res)
    },
    *function_smsLogin({ payload: { phone, smsCode }, callback }, { call }) {
      const res: ResultType = yield call(smsLogin, phone, smsCode)
      callback(res)
    },
    *function_updatePassWord({ payload: { password }, callback }, { call }) {
      const res: ResultType = yield call(updatePassWord, password)
      callback(res)
    },
    *function_forgetPassWord(
      { payload: { phone, smsCode, password }, callback },
      { call }
    ) {
      const res: ResultType = yield call(
        forgetPassWord,
        phone,
        smsCode,
        password
      )
      callback(res)
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {}
  }
}
